<template>
  <span>{{text}}</span>
</template>

<script>
export default {
  name: 'CountDown',
  data() {
    return {
      leftDay: 0,
      leftHour: 0,
      leftMin: 0,
      leftSecond: 0,
      allSeconds: 0
    }
  },
  props: {
    leftMilliSeconds: {
      type: Number,
      default: 0
    }
  },
  computed: {
    text() {
      return `${this.leftDay}天${this.leftHour}小时${this.leftMin}分钟${this.leftSecond}秒`
    }
  },
  methods: {
    beforeCountDown() {
      this.allSeconds = this.leftMilliSeconds / 1000
    },
    convert() {
      const seconds = this.allSeconds
      this.leftSecond = parseInt(seconds % 60)
      this.leftMin = parseInt((seconds / 60) % 60)
      this.leftHour = parseInt((seconds / 60 / 60) % 24)
      this.leftDay = parseInt(seconds / 60 / 60 / 24)
    },
    countDown() {
      this.timer = setTimeout(() => {
        if (this.leftMilliSeconds === 0) {
          clearTimeout(this.timer)
          this.timer = null
        } else {
          this.allSeconds -= 1;
          if (this.allSeconds >= 0) {
            this.convert()
            this.countDown()
          } else {
            clearTimeout(this.timer)
            this.timer = null
          }
        }
      }, 1000)
    },
    start() {
      this.beforeCountDown()
      this.countDown()
    }
  },
  mounted() {
    this.start()
  }
}
</script>

<style>

</style>
